<!-- Web开发在线运行页面 -->
<template>
  <div>
    <el-row :gutter="20">
      <!-- 左侧代码编辑区域 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>代码编辑器</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="runCode">运行代码</el-button>
          </div>
          
          <!-- 代码类型选择 -->
          <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="HTML" name="html">
              <el-input
                v-model="htmlCode"
                type="textarea"
                :rows="15"
                placeholder="请输入HTML代码..."
                @input="autoRun"
              ></el-input>
            </el-tab-pane>
            <el-tab-pane label="CSS" name="css">
              <el-input
                v-model="cssCode"
                type="textarea"
                :rows="15"
                placeholder="请输入CSS代码..."
                @input="autoRun"
              ></el-input>
            </el-tab-pane>
            <el-tab-pane label="JavaScript" name="js">
              <el-input
                v-model="jsCode"
                type="textarea"
                :rows="15"
                placeholder="请输入JavaScript代码..."
                @input="autoRun"
              ></el-input>
            </el-tab-pane>
          </el-tabs>

          <!-- 代码操作按钮 -->
          <div class="code-actions">
            <el-button type="primary" @click="runCode">运行代码</el-button>
            <el-button @click="clearCode">清空代码</el-button>
            <el-button @click="saveCode" :disabled="!canSave">保存代码</el-button>
            <el-button @click="loadCode">加载代码</el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧预览区域 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>实时预览</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshPreview">刷新</el-button>
          </div>
          
          <div class="preview-container">
            <iframe
              ref="previewFrame"
              :srcdoc="previewContent"
              class="preview-frame"
              sandbox="allow-scripts allow-same-origin"
            ></iframe>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 保存代码对话框 -->
    <el-dialog title="保存代码" :visible.sync="saveDialogVisible" width="500px">
      <el-form :model="saveForm" :rules="saveRules" ref="saveForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="saveForm.title" placeholder="请输入代码标题"></el-input>
        </el-form-item>
        <el-form-item label="代码类型" prop="codeType">
          <el-select v-model="saveForm.codeType" placeholder="请选择代码类型">
            <el-option label="HTML" :value="0"></el-option>
            <el-option label="CSS" :value="1"></el-option>
            <el-option label="JavaScript" :value="2"></el-option>
            <el-option label="混合代码" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="saveForm.isPublic"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSave">确定</el-button>
      </div>
    </el-dialog>

    <!-- 加载代码对话框 -->
    <el-dialog title="加载代码" :visible.sync="loadDialogVisible" width="800px">
      <el-table :data="codeList" style="width: 100%" @row-click="selectCode">
        <el-table-column prop="title" label="标题" width="200"></el-table-column>
        <el-table-column prop="codeType" label="类型" width="100">
          <template slot-scope="scope">
            {{ getCodeTypeName(scope.row.codeType) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="loadSelectedCode(scope.row)">加载</el-button>
            <el-button type="text" @click="deleteCode(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WebCodeRunner',
  data() {
    return {
      activeTab: 'html',
      htmlCode: '<h1>Hello World!</h1>\n<p>欢迎使用Web开发在线运行工具</p>',
      cssCode: 'h1 { color: blue; }\np { color: green; }',
      jsCode: 'console.log("Hello from JavaScript!");',
      previewContent: '',
      saveDialogVisible: false,
      loadDialogVisible: false,
      codeList: [],
      saveForm: {
        title: '',
        codeType: 3,
        isPublic: false
      },
      saveRules: {
        title: [
          { required: true, message: '请输入代码标题', trigger: 'blur' }
        ],
        codeType: [
          { required: true, message: '请选择代码类型', trigger: 'change' }
        ]
      },
      autoRunTimer: null
    }
  },
  computed: {
    canSave() {
      return this.htmlCode.trim() || this.cssCode.trim() || this.jsCode.trim()
    }
  },
  methods: {
    // 处理标签页切换
    handleTabClick(tab) {
      // 可以在这里添加标签页切换逻辑
    },

    // 自动运行代码（防抖）
    autoRun() {
      if (this.autoRunTimer) {
        clearTimeout(this.autoRunTimer)
      }
      this.autoRunTimer = setTimeout(() => {
        this.runCode()
      }, 500)
    },

    // 运行代码
    runCode() {
      this.generatePreview()
    },

    // 生成预览内容
    generatePreview() {
      try {
        const cssCode = this.cssCode.trim() ? `<style>\n${this.cssCode}\n</style>\n` : '';
        const htmlCode = this.htmlCode.trim() || '';
        const jsCode = this.jsCode.trim() ? `\n<script>\n${this.jsCode.replace(/<\/script>/g, '<\\/script>')}\n<\/script>\n` : '';
        this.previewContent = `<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<title>Web代码运行结果</title>\n${cssCode}</head>\n<body>\n${htmlCode}${jsCode}\n</body>\n</html>`
      } catch (error) {
        console.error('生成预览内容时出错:', error)
        this.previewContent = `<!DOCTYPE html>\n<html>\n<head>\n<title>错误</title>\n</head>\n<body>\n<h1>代码生成错误</h1>\n<p>请检查您的代码语法</p>\n</body>\n</html>`
      }
    },

    // 清空代码
    clearCode() {
      this.$confirm('确定要清空所有代码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.htmlCode = ''
        this.cssCode = ''
        this.jsCode = ''
        this.previewContent = ''
        this.$message.success('代码已清空')
      })
    },

    // 保存代码
    saveCode() {
      this.saveForm.title = ''
      this.saveForm.codeType = 3
      this.saveForm.isPublic = false
      this.saveDialogVisible = true
    },

    // 确认保存
    confirmSave() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          const codeData = {
            title: this.saveForm.title,
            codeType: this.saveForm.codeType,
            htmlCode: this.htmlCode,
            cssCode: this.cssCode,
            jsCode: this.jsCode,
            isPublic: this.saveForm.isPublic ? 1 : 0
          }

          this.$http({
            url: this.$http.adornUrl('/web/code/save'),
            method: 'post',
            data: this.$http.adornData(codeData)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message.success('代码保存成功')
              this.saveDialogVisible = false
            } else {
              this.$message.error(data.msg || '保存失败')
            }
          }).catch(() => {
            this.$message.error('保存失败，请检查网络连接')
          })
        }
      })
    },

    // 加载代码
    loadCode() {
      this.loadCodeList()
      this.loadDialogVisible = true
    },

    // 加载代码列表
    loadCodeList() {
      this.$http({
        url: this.$http.adornUrl('/web/code/public'),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.codeList = data.data || []
        }
      }).catch(() => {
        // 如果API不存在，使用模拟数据
        this.codeList = [
          {
            id: 1,
            title: '示例HTML页面',
            codeType: 0,
            htmlCode: '<h1>示例页面</h1>',
            cssCode: '',
            jsCode: '',
            createTime: '2024-01-01 00:00:00'
          }
        ]
      })
    },

    // 选择代码
    selectCode(row) {
      this.loadSelectedCode(row)
    },

    // 加载选中的代码
    loadSelectedCode(code) {
      this.htmlCode = code.htmlCode || ''
      this.cssCode = code.cssCode || ''
      this.jsCode = code.jsCode || ''
      this.generatePreview()
      this.loadDialogVisible = false
      this.$message.success('代码加载成功')
    },

    // 删除代码
    deleteCode(id) {
      this.$confirm('确定要删除这个代码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/web/code/${id}`),
          method: 'delete'
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.loadCodeList()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    },

    // 刷新预览
    refreshPreview() {
      this.generatePreview()
      this.$message.success('预览已刷新')
    },

    // 获取代码类型名称
    getCodeTypeName(type) {
      const typeNames = {
        0: 'HTML',
        1: 'CSS',
        2: 'JavaScript',
        3: '混合代码'
      }
      return typeNames[type] || '未知'
    }
  },
  mounted() {
    this.generatePreview()
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.code-actions {
  margin-top: 15px;
  text-align: center;
}

.code-actions .el-button {
  margin: 0 5px;
}

.preview-container {
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.preview-frame {
  width: 100%;
  height: 100%;
  border: none;
  background-color: white;
}

.el-tabs {
  margin-bottom: 15px;
}

.el-textarea {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
}
</style> 